package asia.yuanding.wechat.web.netty.handler.impl;

import asia.yuanding.wechat.web.entity.SessionInfo;
import asia.yuanding.wechat.web.entity.SessionList;
import asia.yuanding.wechat.web.netty.handler.MessageHandlerUtil;
import asia.yuanding.wechat.web.netty.handler.annotation.MessageProcessor;
import asia.yuanding.wechat.web.netty.handler.annotation.NettyMessageHandler;
import asia.yuanding.wechat.web.netty.manager.ChannelManager;
import asia.yuanding.wechat.web.netty.vo.Result;
import asia.yuanding.wechat.web.service.SessionInfoService;
import asia.yuanding.wechat.web.service.SessionListService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 聊天消息处理器
 * 
 * @author Kiro
 */
@Slf4j
@NettyMessageHandler("chat")
public class ChatMessageHandler {

    @Resource
    private SessionInfoService sessionInfoService;

    @Resource
    private SessionListService sessionListService;

    @MessageProcessor("send")
    public String sendMessage(JSONObject reqEntity, ChannelHandlerContext ctx) {
        Map<String, Object> data = reqEntity.get("data", Map.class);
        String contactId = data.get("contactId").toString();
        Channel channel = ChannelManager.getChannel(contactId);
        String content = data.get("content").toString();
        String userId = data.get("createUser").toString();
        String sessionId = data.get("sessionId").toString();
        String createTime = data.get("createTime").toString();
        String messageId = data.get("messageId").toString();

        log.info("用户 {} 向用户 {} 发送消息: {}", userId, contactId, content);

        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setCreateUser(userId);
        sessionInfo.setContent(content);
        sessionInfo.setSessionId(sessionId);
        sessionInfo.setMessageId(messageId);
        sessionInfo.setIsRead(0);

        // 将时间戳字符串转换为 long 类型（去掉小数部分）
        long timestamp = (long) Double.parseDouble(createTime);
        // 使用 Hutool 的 DateUtil 将时间戳转换为 DateTime
        Date dateTime = DateUtil.date(timestamp);
        sessionInfo.setCreateTime(dateTime);

        sessionInfoService.saveMessageAsync(sessionInfo, contactId);

        if (channel != null) {
            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("content", content);
            resultMap.put("contactId", userId);
            resultMap.put("sessionId", sessionId);
            resultMap.put("messageId", messageId);
            resultMap.put("createTime", createTime);
            
            SessionList one = sessionListService.lambdaQuery()
                    .eq(SessionList::getCreateUser, contactId)
                    .eq(SessionList::getSessionId, sessionInfo.getSessionId())
                    .one();
            
            channel.writeAndFlush(MessageHandlerUtil.getResult(Result.ok("userMessage", resultMap)));
        }
        
        // 返回成功响应给发送者
        JSONObject response = new JSONObject();
        response.set("type", "chat");
        response.set("method", "sendResult");
        response.set("success", true);
        response.set("message", "发送成功！");
        response.set("messageId", messageId);
        
        return response.toString();
    }

    @MessageProcessor("history")
    public String getChatHistory(JSONObject reqEntity, ChannelHandlerContext ctx) {
        String targetUserId = reqEntity.getStr("targetUserId");
        String currentUserId = getUserId(ctx);
        int page = reqEntity.getInt("page", 1);
        int size = reqEntity.getInt("size", 20);
        
        log.info("用户 {} 请求与用户 {} 的聊天历史 (页码: {}, 大小: {})", currentUserId, targetUserId, page, size);
        
        JSONObject response = new JSONObject();
        response.set("type", "chat");
        response.set("method", "history");
        response.set("targetUserId", targetUserId);
        response.set("page", page);
        response.set("messages", new JSONObject[0]);
        
        return response.toString();
    }

    @MessageProcessor("typing")
    public String handleTyping(JSONObject reqEntity, ChannelHandlerContext ctx) {
        String toUserId = reqEntity.getStr("toUserId");
        String fromUserId = getUserId(ctx);
        boolean isTyping = reqEntity.getBool("isTyping", false);
        
        log.debug("用户 {} 向用户 {} 发送输入状态: {}", fromUserId, toUserId, isTyping);
        
        JSONObject response = new JSONObject();
        response.set("type", "chat");
        response.set("method", "typing");
        response.set("fromUserId", fromUserId);
        response.set("isTyping", isTyping);
        
        return response.toString();
    }

    private String getUserId(ChannelHandlerContext ctx) {
        Object userId = ctx.channel().attr(AttributeKey.valueOf("uId")).get();
        return userId != null ? userId.toString() : "unknown";
    }
}